package li.nibble.twittertido;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import li.nibble.twittertido.beans.Tweet;
import li.nibble.twittertido.lazyimage.ImageLoader;
import li.nibble.twittertido.webservice.Client;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class Sender extends Activity {

	private Tweet tweet = new Tweet();
	String id = "";

	TextView tt;
	TextView tu;
	ImageView iv;
	Button send;
	ProgressBar loading;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sender);

		tt = (TextView) findViewById(R.id.tweet_text);
		tu = (TextView) findViewById(R.id.tweet_user);
		iv = (ImageView) findViewById(R.id.avatar);
		send = (Button) findViewById(R.id.send);
		loading = (ProgressBar) findViewById(R.id.loading);

		Intent intent = getIntent();
		String action = intent.getAction();
		String type = intent.getType();

		initAds();
		boolean error = false;
		boolean forbidden = false;

		String sharedText = "";
		if (Intent.ACTION_SEND.equals(action) && type != null) {
			if ("text/plain".equals(type)) {
				sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
				if (sharedText != null) {
					id = sharedText.substring(sharedText.length() - 18);
					if (IsURLTwitter(sharedText)) {
						tweet = Utils.getTweet(id);
					} else if (getTweetText(sharedText) != null) {
						tweet = getTweetText(sharedText);
					} else {
						Log.e(Sender.class.getName(), "No es tweet");
						error = true;
					}
				}
			}
		} 

		if (tweet != null) {

			tt.setText(tweet.getTweet());
			tu.setText(tweet.getUser());

			new ImageLoader(this).DisplayImage(
					"https://api.twitter.com/1/users/profile_image?screen_name="
							+ tweet.getUser() + "&size=bigger", iv);
		} else {
			error = true;
			forbidden = true;
		}

		if (error) {
			LinearLayout ll_tweet = (LinearLayout) findViewById(R.id.ll_tweet);
			ll_tweet.setVisibility(View.GONE);
			tt.setVisibility(View.GONE);
			tu.setVisibility(View.GONE);
			TextView error_text = (TextView) findViewById(R.id.error_txt);
			if (forbidden) {
				error_text
						.setText("Es posible que el tweet que desea enviar se encuentre protegido. Lo sentimos");
			} else {
				error_text
						.setText("No hemos podido reconocer el tweet, inténtalo de nuevo o mira el procedimiento, puede que nos hayamos explicado mal");
			}

			error_text.setVisibility(View.VISIBLE);
			send.setText("Aceptar");
			send.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					startActivity(new Intent(getApplicationContext(),
							Main.class));
				}
			});

		} else {
			send.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					loading.setVisibility(View.VISIBLE);
					send.setVisibility(View.INVISIBLE);
					new SendTask().execute();
				}
			});
		}
	}

	private boolean IsURLTwitter(String url) {
		String regex = "^((http|https)://(www\\.)?(mobile\\.)?twitter.com/)(#!/)?[A-Za-z0-9-_]{0,15}/status/[0-9]{18}";
		try {
			Pattern patt = Pattern.compile(regex);
			Matcher matcher = patt.matcher(url);
			return matcher.matches();
		} catch (RuntimeException e) {
			return false;
		}
	}

	private Tweet getTweetText(String text) {
		Tweet t = new Tweet();
		try {
			int end_tweet = text.lastIndexOf("-") - 1;
			t.setTweet(text.substring(0, end_tweet).replace("—", "-"));
//			Log.e("Tweet",t.getTweet());
			t.setDate(new Date().toString());
			t.setUrlImage("");
			int startUser = text.lastIndexOf("(") + 2;
			int endUser = text.lastIndexOf(")");
			t.setUser(text.substring(startUser, endUser));
		} catch (Exception e) {
			return null;
		}
		if (!(text.contains("--") && text.contains(")") && text.contains("(") && text
				.contains("@"))) {
			return null;
		}

		return t;
	}

	public class SendTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			// Simulates a background job.
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void voids) {
			Client.sendTweet(Sender.this, tweet, id);
			startActivity(new Intent(Sender.this, Main.class));
		}
	}

	private void initAds() {
		AdView adView = new AdView(this, AdSize.BANNER, Constants.ADMOB);
		LinearLayout layout = (LinearLayout) findViewById(R.id.ads);
		layout.addView(adView);
		adView.loadAd(new AdRequest());
	}
}
